package br.ufrj.dcc.dojo.jtrace.texture;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.jtrace.Hit;
import org.jtrace.Jay;
import org.jtrace.geometry.GeometricObject;
import org.jtrace.geometry.MeshObject;
import org.jtrace.geometry.Sphere;
import org.jtrace.geometry.Triangle;
import org.jtrace.lights.Light;
import org.jtrace.primitives.ColorRGB;
import org.jtrace.primitives.Point2D;
import org.jtrace.primitives.Point3D;
import org.jtrace.primitives.Vector3D;
import org.jtrace.shader.Shader;

public abstract class TextureShader implements Shader {

    BufferedImage texture;

    public TextureShader(String filename) throws IOException {
    	File file = new File(filename);
    	texture = ImageIO.read(file);
    	texture.getRGB(0, 0);
	}
    
	@Override
	public final ColorRGB shade(Light light, Hit hit, Jay jay, GeometricObject object) {
		if (object instanceof Sphere) {
			final Sphere sphere = (Sphere) object;
			return getColor(hit, jay, object, sphere.getCenter(), sphere.getRadius()*2);
		} else if (object instanceof Triangle){
			final Triangle triangle = (Triangle) object;
			final MeshObject mesh = triangle.getMesh();
			if (mesh != null) {
				double height = Math.abs( hit.getPoint(jay).getZ() - mesh.getCenter().getZ() ) * 2;
				return getColor(hit, jay, object, mesh.getCenter(), height);
			}
		}
		return new ColorRGB(0, 0, 0);
	}

	public abstract Point2D getPoint2DFromMapping(Vector3D intersectVector, double cilinderHeight);
	
	protected final ColorRGB getColor(Hit hit, Jay jay, GeometricObject object, Point3D center, double cilinderHeight) {
		Point3D hitPoint = hit.getPoint(jay);
		Vector3D vp = new Vector3D(center, hitPoint);
		Point2D coord = getPoint2DFromMapping(vp, cilinderHeight);
		
		int width = texture.getWidth();
		int height = texture.getHeight();
		System.out.println( "Largura textura: " + width);
		System.out.println( "Altura textura: " + height);
		int x = (int) (coord.getX() * width);
		int y = (int) (coord.getY() * height);
		System.out.println("Pontos na textura: " + x + " , " + y);
		int rgb = texture.getRGB(x, y);
		return new ColorRGB(rgb);
	}

}